// pages/teamShare/teamShare.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    qrcodeUrl: '',  //https://cqymzp.top/img/Upload/qrcode.jpg
    bg: '',
    posterShow: false,
    postImage: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let res1 = await this.getAccessToken();
    let res2 = await this.getQrcode(res1.data.access_token);
    let base64 = wx.arrayBufferToBase64(res2.data); 
    base64　= 'data:image/jpeg;base64,' + base64
    this.setData({
      qrcodeUrl: base64
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getAccessToken() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/token',
        method: 'GET',
        data: {
          grant_type: 'client_credential',
          appid: 'wxe7d495ef6e3923e7',
          secret: '5cb925b13bfe936b17aa78615cbc645c'
        },
        success: function (res) {
          resolve(res)
        }
      })
    })
  },
  getQrcode(token) {
    return new Promise((resolve, reject) => {
      let accountId = app.globalData.accountId;
      wx.request({
        url: 'https://api.weixin.qq.com/wxa/getwxacode?access_token='+token,
        method: 'POST',
        responseType: 'arraybuffer',
        data: {
          path: `?shareId=${accountId}&type=team`
        },
        success: function (res) {
          resolve(res)
        }
      })
    })
  },
  getImage() {
    let _this = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        
        _this.setData({
          bg: tempFilePaths[0]
        })
      }
    })
  },
  onClose() {
    this.setData({
      posterShow: false
    })
  },
  saveImage: async function() {
    wx.showLoading({
      title: '海报生成中...'
    });
    let self = this;
    const ctx = wx.createCanvasContext('myCanvas');
    ctx.setFillStyle('white')
    ctx.fillRect(0, 0, 276, 444)
    wx.downloadFile({
      url: self.data.bg, //海报
      success: async function (res) {
        let post = res.tempFilePath;
        let { width, height } = await self.getSize(post);
        let actWidth =  height*(276/355);
        let coord = [
          (width - actWidth)/2,
          0,
          actWidth,
          height,
        ];
        console.log(coord);
        // wx.downloadFile({
        //   url: self.data.qrcodeUrl, //个人logo
        //   success: function(res) {
            
        //   },
        //   fail: function(res) {
        //     wx.showToast({
        //       title: '头像下载失败,请重新生成1',
        //       icon: 'none'
        //     })
        //   }
        // });
        let logo = self.data.qrcodeUrl
        wx.hideLoading();
        // ctx.drawImage(post, 540,0,839,1080,0,0,276,355);
        ctx.drawImage(post, coord[0], coord[1], coord[2], coord[3],0,0,276,355);
        ctx.fillStyle = "#fff";
        ctx.fillRect(95, 306, 86, 86); 
        ctx.drawImage(logo, 97, 308, 82, 82);
        ctx.setFontSize(12)
        ctx.setFillStyle('#333');
        ctx.setFontSize(12)
        ctx.setFillStyle('#fb5e2c');
        //长按识别打开小程序文字位置
        ctx.setFontSize(12)
        ctx.setFillStyle('#333');
        ctx.fillText('长按识别打开小程序', (276 - ctx.measureText('长按识别打开小程序').width) / 2, 410)
        ctx.draw(false, function(e) {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 375,
            height: 417,
            quality: 1,
            canvasId: 'myCanvas',
            success: function(respon) {
              ctx.setFillStyle('white')
              self.setData({
                postImage: respon.tempFilePath,
                posterShow: true
              })
            },
            fail: function(res) {
              wx.showToast({
                title: 'canvasToTempFilePath---fail',
                icon: 'none'
              })
            }
          });
        });
      },
      fail: function(res) {
        console.log(res);
        wx.showToast({
          title: '下载失败,请重新生成2',
          icon: 'none'
        })
      }
    })
  },
  // 获取背景图片尺寸
  getSize(url) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success (res) {
          console.log(res.width)
          console.log(res.height)
          resolve(res)
        }
      })
    })
  },
// 2、点击保存到相册时做授权处理
  save: function() {
    var _this = this;
    wx.getSetting({
      success(res) {
        console.log(res)
        if (res.authSetting['scope.writePhotosAlbum'] != undefined && res.authSetting['scope.writePhotosAlbum'] != true) {
          wx.showModal({
            title: '提示',
            content: '您未授权保存到相册,确认授权?',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.writePhotosAlbum"] == true) {
                    } else {
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: _this.data.postImage,
            success(res) {
              console.log('保存成功---ok')
              wx.showToast({
                title: '保存成功',
                icon: 'none'
              })
            }
          })
        }
      },
      fail: function(e) {
        console.log(999)
      }
    });
  
  }

})